package com.runfast.common.web.interceptor;

import com.runfast.common.utils.SpringUtils;
import com.runfast.common.web.shiro.UrlPermission;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author: lijin
 * @date: 2018年03月01日
 */
public class UrlPermissionInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            UrlPermission methodAnnotation = handlerMethod.getMethodAnnotation(UrlPermission.class);
            if (methodAnnotation != null) {

                ApplicationContext applicationContext = SpringUtils.getApplicationContext();
                String url = null;
                a:
                for (Map.Entry<String, AbstractHandlerMethodMapping> bean : applicationContext
                        .getBeansOfType(AbstractHandlerMethodMapping.class).entrySet()) {
                    @SuppressWarnings("unchecked")
                    Map<?, HandlerMethod> methods = bean.getValue().getHandlerMethods();
                    for (Map.Entry<?, HandlerMethod> methodEntry : methods.entrySet()) {
                        if (methodEntry.getValue().getMethod() != handlerMethod.getMethod()) continue;
                        else {
                            url = methodEntry.getKey().toString();
                            break a;
                        }
                    }
                }
                if (url != null) {
                    Subject subject = SecurityUtils.getSubject();
                    subject.checkPermission(url);
                }

            }
        }
        return true;
    }


}
